import { createSlice } from "@reduxjs/toolkit";

export const counterSlice = createSlice({
  name: "counter",
  initialState: {
    counter: 0,
  },
  /**
   * Redux Toolkit 允许我们在 reducers 中编写 mutating 逻辑。
     它实际上并没有 mutate state 因为它使用了 Immer 库，
     它检测到草稿 state 的变化并产生一个全新的基于这些更改的不可变 state
   */
  // reducers里的方法相当于是 mutations,修改 state的值
  reducers: {
    add: (state) => {
      state.counter += 1;
    },
    reduce: (state) => {
      state.counter -= 1;
    },
    addByPayload: (state, action) => {
      /**
       * action destructor
       * payload: 5
       * type: "counter/addByPayload"
       */
      console.log("🚀 ~ action:", action);
      console.log("🚀 ~ state:", state);
      state.counter += action.payload;
    },
  },
});

// export reducer's actions.
export const { add, reduce, addByPayload } = counterSlice.actions;

// export the reducer
export default counterSlice.reducer; // Reducer<{code: number}>
